/**
 * Service基础层统一导出
 */

// 现代化Service基类
export { ModernBaseService } from './ModernBaseService';

// 遗留Service适配器
export { 
    LegacyServiceAdapter,
    staticToInstance,
    asyncStaticToInstance,
    createServiceProxy 
} from './LegacyServiceAdapter';

// 重新导出基础设施层
export { BaseService } from '../../infrastructure/base/BaseService';
export { BaseController } from '../../infrastructure/base/BaseController';
export { BaseComponent } from '../../infrastructure/base/BaseComponent';

/**
 * Service类型定义
 */
export interface ServiceConstructor<T> {
    new (container?: any): T;
}

export interface ServiceInstance {
    init(): Promise<void>;
    destroy(): Promise<void>;
    isReady(): boolean;
    getServiceName(): string;
}

/**
 * Service管理器
 * 提供Service的统一管理和生命周期控制
 */
export class ServiceManager {
    private static services = new Map<string, ServiceInstance>();
    private static initialized = false;

    /**
     * 注册Service
     * @param name Service名称
     * @param service Service实例
     */
    static registerService(name: string, service: ServiceInstance): void {
        if (this.services.has(name)) {
            console.warn(`Service ${name} is already registered. Overwriting...`);
        }
        
        this.services.set(name, service);
        console.log(`Service registered: ${name}`);
    }

    /**
     * 获取Service
     * @param name Service名称
     * @returns Service实例
     */
    static getService<T extends ServiceInstance>(name: string): T | undefined {
        return this.services.get(name) as T;
    }

    /**
     * 初始化所有Service
     */
    static async initializeAll(): Promise<void> {
        if (this.initialized) {
            console.warn('Services already initialized');
            return;
        }

        console.log('Initializing all services...');
        const initPromises: Promise<void>[] = [];

        for (const [name, service] of this.services) {
            if (!service.isReady()) {
                initPromises.push(
                    service.init().catch(error => {
                        console.error(`Failed to initialize service ${name}:`, error);
                        throw error;
                    })
                );
            }
        }

        await Promise.all(initPromises);
        this.initialized = true;
        console.log('All services initialized successfully');
    }

    /**
     * 销毁所有Service
     */
    static async destroyAll(): Promise<void> {
        console.log('Destroying all services...');
        const destroyPromises: Promise<void>[] = [];

        for (const [name, service] of this.services) {
            if (service.isReady()) {
                destroyPromises.push(
                    service.destroy().catch(error => {
                        console.error(`Failed to destroy service ${name}:`, error);
                    })
                );
            }
        }

        await Promise.all(destroyPromises);
        this.services.clear();
        this.initialized = false;
        console.log('All services destroyed');
    }

    /**
     * 获取所有已注册的Service名称
     */
    static getRegisteredServices(): string[] {
        return Array.from(this.services.keys());
    }

    /**
     * 获取Service状态统计
     */
    static getServiceStatus(): {
        total: number;
        ready: number;
        notReady: number;
        services: Array<{ name: string; ready: boolean }>;
    } {
        const services = Array.from(this.services.entries()).map(([name, service]) => ({
            name,
            ready: service.isReady()
        }));

        const ready = services.filter(s => s.ready).length;
        const notReady = services.filter(s => !s.ready).length;

        return {
            total: services.length,
            ready,
            notReady,
            services
        };
    }

    /**
     * 重启指定Service
     * @param name Service名称
     */
    static async restartService(name: string): Promise<void> {
        const service = this.services.get(name);
        if (!service) {
            throw new Error(`Service ${name} not found`);
        }

        console.log(`Restarting service: ${name}`);
        
        if (service.isReady()) {
            await service.destroy();
        }
        
        await service.init();
        console.log(`Service restarted: ${name}`);
    }

    /**
     * 检查是否所有Service都已就绪
     */
    static areAllServicesReady(): boolean {
        return Array.from(this.services.values()).every(service => service.isReady());
    }
}
